<script setup>
import { nextTick, ref } from 'vue';
import { getRoleDetailService, editRoleService } from '@/apis/system-manage';

const roleModelRef = ref();
const roleModel = ref({});

const loading = ref(false);

let isGiveupWarning = false;
const handleClose = (done) => {
  // 判断是否有部分表单已经赋值了
  var hasValueProps = Object.keys(roleModel.value).filter(
    (key) => roleModel.value[key]
  );
  if (hasValueProps.length > 0) {
    if (!isGiveupWarning) {
      ElMessage.warning('当前的 角色 未保存，放弃保存请再次点击取消');
      isGiveupWarning = true;
      setTimeout(() => {
        isGiveupWarning = false;
      }, 3000);
      return;
    }
  }

  if (done) {
    done();
  } else {
    dialogVisible.value = false;
  }
};

const rules = ref({
  roleName: [
    {
      required: true,
      message: '请输入 角色 名称',
      trigger: 'blur'
    }
  ],
  roleCode: [
    {
      required: true,
      message: '请输入 角色编码',
      trigger: 'blur'
    }
  ]
});

const dialogVisible = ref(false);
const title = ref('');
const open = async (id) => {
  nextTick(() => {
    roleModelRef.value &&
      roleModelRef.value.clearValidate &&
      roleModelRef.value.clearValidate();
  });
  roleModel.value = {};

  dialogVisible.value = true;
  title.value = id ? '编辑角色' : '新增角色';

  if (id) {
    loading.value = true;
    let res = await getRoleDetailService({ id: id });
    loading.value = false;
    roleModel.value = res.data;
  }
};

defineExpose({
  open
});

const emit = defineEmits(['finishEdit']);

const onConfirm = async () => {
  await roleModelRef.value.validate();
  let roleModelCopy = JSON.parse(JSON.stringify(roleModel.value));
  loading.value = true;
  let res = await editRoleService(roleModelCopy);
  loading.value = false;
  ElMessage.success(res.msg);
  dialogVisible.value = false;
  emit('finishEdit');
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="30%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      v-loading="loading"
      ref="roleModelRef"
      :model="roleModel"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleModel.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="roleModel.roleCode"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onConfirm">确认</el-button>
        <el-button @click="handleClose()">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.role-icon-container i {
  font-size: 30px;
  margin-left: 30px;
}
</style>
